/**
 * 表单验证工具函数
 */

import { ValidationRule, ValidationResult, Patterns, ValidationRules } from './types';

/**
 * 验证单个字段
 * @param value 字段值
 * @param rule 验证规则
 * @returns 验证结果
 */
export function validateField(value: string, rule: ValidationRule): ValidationResult {
  const errors: string[] = [];

  // 必填验证
  if (rule.required && (!value || value.trim() === '')) {
    errors.push('此字段为必填项');
    return { isValid: false, errors };
  }

  // 如果值为空且不是必填，则验证通过
  if (!value || value.trim() === '') {
    return { isValid: true, errors: [] };
  }

  // 最小长度验证
  if (rule.minLength && value.length < rule.minLength) {
    errors.push(`最少需要${rule.minLength}个字符`);
  }

  // 最大长度验证
  if (rule.maxLength && value.length > rule.maxLength) {
    errors.push(`最多允许${rule.maxLength}个字符`);
  }

  // 正则表达式验证
  if (rule.pattern && !rule.pattern.test(value)) {
    errors.push(rule.message);
  }

  return {
    isValid: errors.length === 0,
    errors
  };
}

/**
 * 验证手机号
 * @param phone 手机号
 * @returns 验证结果
 */
export function validatePhone(phone: string): ValidationResult {
  return validateField(phone, ValidationRules.phone);
}

/**
 * 验证邮箱
 * @param email 邮箱
 * @returns 验证结果
 */
export function validateEmail(email: string): ValidationResult {
  return validateField(email, ValidationRules.email);
}

/**
 * 验证密码
 * @param password 密码
 * @returns 验证结果
 */
export function validatePassword(password: string): ValidationResult {
  return validateField(password, ValidationRules.password);
}

/**
 * 验证用户名
 * @param username 用户名
 * @returns 验证结果
 */
export function validateUsername(username: string): ValidationResult {
  return validateField(username, ValidationRules.username);
}

/**
 * 验证验证码
 * @param code 验证码
 * @returns 验证结果
 */
export function validateVerifyCode(code: string): ValidationResult {
  return validateField(code, ValidationRules.verifyCode);
}

/**
 * 验证密码确认
 * @param password 密码
 * @param confirmPassword 确认密码
 * @returns 验证结果
 */
export function validatePasswordConfirm(password: string, confirmPassword: string): ValidationResult {
  const errors: string[] = [];
  
  if (!confirmPassword || confirmPassword.trim() === '') {
    errors.push('请确认密码');
  } else if (password !== confirmPassword) {
    errors.push('两次输入的密码不一致');
  }

  return {
    isValid: errors.length === 0,
    errors
  };
}

/**
 * 验证账号（手机号或邮箱）
 * @param account 账号
 * @returns 验证结果
 */
export function validateAccount(account: string): ValidationResult {
  if (!account || account.trim() === '') {
    return { isValid: false, errors: ['请输入手机号或邮箱'] };
  }

  // 判断是手机号还是邮箱
  if (Patterns.phone.test(account)) {
    return validatePhone(account);
  } else if (Patterns.email.test(account)) {
    return validateEmail(account);
  } else {
    return { isValid: false, errors: ['请输入正确的手机号或邮箱格式'] };
  }
}

/**
 * 验证登录表单
 * @param data 登录表单数据
 * @returns 验证结果
 */
export function validateLoginForm(data: { account: string; password: string }): ValidationResult {
  const errors: string[] = [];

  // 验证账号
  const accountResult = validateAccount(data.account);
  if (!accountResult.isValid) {
    errors.push(...accountResult.errors);
  }

  // 验证密码
  const passwordResult = validatePassword(data.password);
  if (!passwordResult.isValid) {
    errors.push(...passwordResult.errors);
  }

  return {
    isValid: errors.length === 0,
    errors
  };
}

/**
 * 验证注册表单
 * @param data 注册表单数据
 * @returns 验证结果
 */
export function validateRegisterForm(data: {
  username: string;
  password: string;
  confirmPassword: string;
  phone: string;
  email?: string;
  verifyCode: string;
}): ValidationResult {
  const errors: string[] = [];

  // 验证用户名
  const usernameResult = validateUsername(data.username);
  if (!usernameResult.isValid) {
    errors.push(...usernameResult.errors);
  }

  // 验证手机号
  const phoneResult = validatePhone(data.phone);
  if (!phoneResult.isValid) {
    errors.push(...phoneResult.errors);
  }

  // 验证邮箱（可选）
  if (data.email) {
    const emailResult = validateEmail(data.email);
    if (!emailResult.isValid) {
      errors.push(...emailResult.errors);
    }
  }

  // 验证密码
  const passwordResult = validatePassword(data.password);
  if (!passwordResult.isValid) {
    errors.push(...passwordResult.errors);
  }

  // 验证确认密码
  const confirmResult = validatePasswordConfirm(data.password, data.confirmPassword);
  if (!confirmResult.isValid) {
    errors.push(...confirmResult.errors);
  }

  // 验证验证码
  const codeResult = validateVerifyCode(data.verifyCode);
  if (!codeResult.isValid) {
    errors.push(...codeResult.errors);
  }

  return {
    isValid: errors.length === 0,
    errors
  };
}

/**
 * 验证重置密码表单
 * @param data 重置密码表单数据
 * @returns 验证结果
 */
export function validateResetPasswordForm(data: {
  phone: string;
  verifyCode: string;
  newPassword: string;
  confirmPassword: string;
}): ValidationResult {
  const errors: string[] = [];

  // 验证手机号
  const phoneResult = validatePhone(data.phone);
  if (!phoneResult.isValid) {
    errors.push(...phoneResult.errors);
  }

  // 验证验证码
  const codeResult = validateVerifyCode(data.verifyCode);
  if (!codeResult.isValid) {
    errors.push(...codeResult.errors);
  }

  // 验证新密码
  const passwordResult = validatePassword(data.newPassword);
  if (!passwordResult.isValid) {
    errors.push(...passwordResult.errors);
  }

  // 验证确认密码
  const confirmResult = validatePasswordConfirm(data.newPassword, data.confirmPassword);
  if (!confirmResult.isValid) {
    errors.push(...confirmResult.errors);
  }

  return {
    isValid: errors.length === 0,
    errors
  };
}

/**
 * 显示验证错误消息
 * @param errors 错误数组
 */
export function showValidationErrors(errors: string[]): void {
  if (errors.length > 0) {
    wx.showToast({
      title: errors[0], // 只显示第一个错误
      icon: 'none',
      duration: 2000
    });
  }
}

/**
 * 验证并显示错误
 * @param value 值
 * @param rule 规则
 * @returns 是否验证通过
 */
export function validateAndShow(value: string, rule: ValidationRule): boolean {
  const result = validateField(value, rule);
  if (!result.isValid) {
    showValidationErrors(result.errors);
  }
  return result.isValid;
} 